package solicitudes.dao.impl;

import java.util.List;
import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import solicitudes.dao.DAOCompra;
import solicitudes.entity.Compra;

/***
 * 
 * @author MARIA ALEJANDRA CELEMIN R.
 * @version 1.0
 * 
 * Clase que implementa los metodos de la interfaz DAOCompra
 * @see DAOCompra
 *
 */
public class DAOCompraImpl extends HibernateDaoSupport implements DAOCompra {

	private static Logger logger = Logger.getLogger(DAOCompraImpl.class);
	
	/* (non-Javadoc)
	 * @see solicitudes.dao.DAOCompra#obtenerCompras()
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Compra> obtenerCompras() {
		
		Session session = getSession(); 
		List<Compra> compras = new ArrayList<Compra>();
		
		try {
			compras = session.createQuery("from Compra").list();
		} catch (HibernateException ex) {
			logger.debug("Exception encontrada" + ex.getLocalizedMessage());
		} finally {
			session.close();
		}
		
		return compras;
	}

	/* (non-Javadoc)
	 * @see solicitudes.dao.DAOCompra#obtenerCompra()
	 */
	@Override
	public Compra obtenerCompra(Integer codCompra){
	
		Session session = getSession();
		Compra comp = null;
		
		try {
			comp = (Compra) session.get(Compra.class, codCompra);
		} catch (HibernateException ex) {
			logger.debug("Exception encontrada" + ex.getLocalizedMessage());
		} finally {
			session.close();
		}
		
		return comp;
	}

	/* (non-Javadoc)
	 * @see solicitudes.dao.DAOCompra#guardarCompra(solicitudes.entity.Compra)
	 */
	@Override
	public void guardarCompra(Compra comp) {
		
		Session session = getSession(); 
		session.beginTransaction();
		
		try {
			session.save(comp);
			session.getTransaction().commit();
			
		} catch (HibernateException ex) {
			logger.debug("Exception encontrada" + ex.getLocalizedMessage());
		} finally {
			session.close();
		}		
	}

	/* (non-Javadoc)
	 * @see solicitudes.dao.DAOCompra#eliminarCompra(solicitudes.entity.Compra)
	 */
	@Override
	public void eliminarCompra(Compra comp) {
		
		Session session = getSession(); 
		session.beginTransaction();
		
		try {
			session.delete(comp);
			session.getTransaction().commit();
		} catch (HibernateException ex) {
			logger.debug("Exception encontrada" + ex.getLocalizedMessage());
		} finally {
			session.close();
		}
		
	}

	/* (non-Javadoc)
	 * @see solicitudes.dao.DAOCompra#editarCompra(solicitudes.entity.Compra)
	 */
	@Override
	public void editarCompra(Compra comp) {
		
		Session session = getSession();
		session.beginTransaction();
		
		try {
			session.merge(comp);
			session.getTransaction().commit();
		} catch (HibernateException ex) {
			logger.debug("Exception encontrada" + ex.getLocalizedMessage());
		} finally {
			session.close();
		}
		
	}

}
